<template>
  <div class="notice-board">
    <h2>宠物公告栏</h2>

    <!-- 搜索框 -->
    <input
        v-model="searchQuery"
        type="text"
        placeholder="搜索公告..."
        class="search-input"
        @input="onSearchInput"
    />

    <!-- 排序选项 -->
    <div class="sort-options">
      <label for="sortBy">排序方式：</label>
      <select v-model="sortBy" id="sortBy" @change="sortData">
        <option value="date">按日期排序</option>
        <option value="title">按标题排序</option>
      </select>
    </div>

    <!-- 显示公告列表 -->
    <ul>
      <li v-for="(notice, index) in paginatedNotices" :key="index">
        <strong>{{ notice.title }}</strong>:
        <span class="notice-message" :title="notice.message">{{ notice.content }}</span>
        <br />
        <small>发布于: {{ notice.releasetime }}</small>
      </li>
    </ul>

    <!-- 没有数据时的提示 -->
    <div v-if="paginatedNotices.length === 0">
      <p>目前没有符合条件的公告信息。</p>
    </div>

    <!-- 分页按钮和页码输入框 -->
    <div class="pagination">
      <button @click="goToPage(currentPage - 1)" :disabled="currentPage === 1">上一页</button>

      <!-- 页码输入框 -->
      <input
          v-model="pageInput"
          type="number"
          :min="1"
          :max="totalPages"
          @change="goToPage(pageInput)"
          class="page-input"
          placeholder="页码"
      />

      <button @click="goToPage(currentPage + 1)" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </div>
</template>

<script>
import { findAllNotice, findNotice } from '../../api/user.js';

function debounce(fn, delay) {
  let timer;
  return function (...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

export default {
  name: 'PetNoticeBoard',
  data() {
    return {
      notices: [], // 所有公告数据
      searchQuery: '', // 搜索关键词
      sortBy: 'date', // 排序方式
      currentPage: 1, // 当前页码
      pageSize: 3, // 每页显示的公告数量
      pageInput: 1, // 页码输入框的值
    };
  },
  computed: {
    // 过滤后的公告列表
    filteredNotices() {
      const query = this.searchQuery.toLowerCase();
      return this.notices.filter((notice) => {
        return (
            notice.title.toLowerCase().includes(query) ||
            notice.content.toLowerCase().includes(query)
        );
      });
    },
    // 排序后的公告列表
    sortedNotices() {
      const filtered = this.filteredNotices;
      return filtered.sort((a, b) => {
        if (this.sortBy === 'title') {
          return a.title.localeCompare(b.title);
        } else {
          return new Date(b.releasetime) - new Date(a.releasetime);
        }
      });
    },
    // 分页后的公告列表
    paginatedNotices() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.sortedNotices.slice(start, end);
    },
    // 总页数
    totalPages() {
      return Math.ceil(this.sortedNotices.length / this.pageSize);
    },
  },
  methods: {
    // 获取所有公告
    async fetchNotices() {
      try {
        const response = await findAllNotice();
        console.log('Notices fetched successfully:', response.data.data);
        this.notices = response.data.data; // 假设后端返回的数据在 response.data.data 中
      } catch (error) {
        console.error('Error fetching notices:', error);
      }
    },
    // 搜索输入框的防抖处理
    onSearchInput: debounce(function () {
      this.performSearch();
    }, 300),
    // 执行搜索
    async performSearch() {
      try {
        let response;
        if (this.searchQuery.trim() === '') {
          // 如果搜索框为空，则加载所有公告
          response = await findAllNotice();
        } else {
          // 否则调用搜索接口
          response = await findNotice(this.searchQuery);
        }
        console.log('Search results fetched successfully:', response.data.data);
        this.notices = response.data.data; // 更新公告数据
        this.currentPage = 1; // 重置页码为第一页
        this.pageInput = 1; // 重置页码输入框
      } catch (error) {
        console.error('Error searching notices:', error);
      }
    },
    // 排序数据（计算属性会自动更新，无需额外操作）
    sortData() {
      // 无需手动操作，计算属性会自动处理
    },
    // 跳转到指定页码
    goToPage(page) {
      const validPage = Math.max(1, Math.min(page, this.totalPages));
      this.currentPage = validPage;
      this.pageInput = validPage;
    },
  },
  mounted() {
    // 组件加载时获取所有公告
    this.fetchNotices();
  },
};
</script>

<style scoped>
.notice-board {
  border: 2px solid #ccc;
  padding: 20px;
  width: 800px;
  height: 550px;
  margin: 0 auto;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
}

.notice-board h2 {
  text-align: center;
  font-size: 1.8em;
  color: #333;
  margin-bottom: 30px;
  font-weight: bold;
}

.search-input {
  width: 700px;
  padding: 8px;
  margin-bottom: 15px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 1em;
}

.sort-options {
  margin-bottom: 20px;
}

.sort-options label {
  margin-right: 10px;
}

select {
  padding: 5px 10px;
  font-size: 1em;
  border-radius: 5px;
  border: 1px solid #ccc;
}

ul {
  list-style-type: none;
  padding: 0;
  margin-top: 20px;
}

li {
  margin: 10px 0;
  padding: 10px;
  background-color: #fafafa;
  border: 1px solid #ddd;
  border-radius: 5px;
  text-align: left;
}

li strong {
  color: #007bff;
}

.notice-message {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
}

.notice-message:hover {
  -webkit-line-clamp: unset;
  overflow: visible;
  white-space: normal;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.pagination button {
  padding: 5px 15px;
  margin: 0 10px;
  font-size: 1em;
  cursor: pointer;
}

.pagination button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-input {
  width: 60px;
  padding: 5px;
  font-size: 1em;
  margin: 0 10px;
  border-radius: 5px;
  border: 1px solid #ccc;
  text-align: center;
}
</style>